<template>
    <div class="content">
      <!-- 人工审核 -->
    <div class="manual-review">
      <card>
        <template slot="header">
          <h3 class="card-title">📝 人工审核</h3>
        </template>

        <el-table :data="questions" border style="width: 100%">
          <el-table-column prop="question" label="题目" width="300"></el-table-column>
          <el-table-column prop="aiAnswer" label="大模型答案"></el-table-column>
          <el-table-column label="标准答案">
            <template slot-scope="{ row }">
              {{ row.answer === 1 ? 'true' : row.answer === 0 ? 'false' : row.answer }}
            </template>
          </el-table-column>

          <el-table-column label="审核结果" width="180">
            <template slot-scope="{ row }">
              <el-select v-model="row.score" v-if="row.type === 'choice' || row.type === 'true_false'" placeholder="请选择"> 
                <el-option :value="10" label="请选择" disabled></el-option>               
                <el-option :value="1" label="✔ 正确"></el-option>
                <el-option :value="0" label="❌ 错误"></el-option>
              </el-select>
              <star-rating v-if="row.type === 'short_answer'" v-model="row.score" :max-rating="5" :star-size="30" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template slot-scope="{ row }">
              <el-button type="primary" size="mini" @click="submitManualReview(row)">提交</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->

        <div class="pagination">
          <el-button @click="prevPage" :disabled="currentPage === 1">上一页</el-button>
          <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          <el-button @click="nextPage" :disabled="currentPage === totalPages">下一页</el-button>
        </div>
      </card>
    </div>
  
      <!-- 自动审核 -->
      <div class="auto-review">
        <card>
          <template slot="header">
            <h3 class="card-title">⚙️ 自动审核</h3>
          </template>
  
          <div class="col-12 mt-4">
            <card>
              <base-button 
                type="success" 
                class="mt-3" 
                @click="startReview"
                :disabled="isEvaluating"
              >
                {{ isEvaluating ? '审核中...' : '开始审核' }}
              </base-button>
            </card>
            <!-- 改进的进度条 -->
            <div v-if="isEvaluating || showCompletedProgress" class="progress-container">
              <div class="progress-info">
                <span class="progress-label">审核进度</span>
                <span class="progress-percentage">{{ displayProgress }}%</span>
              </div>
              <el-progress 
                :percentage="displayProgress" 
                :stroke-width="16"
                :color="customColorMethod"
                :show-text="false"
                class="custom-progress"
              ></el-progress>
              <div class="progress-status">
                <span v-if="displayProgress < 100">审核引擎正在审核中，请稍候...</span>
                <span v-else class="completed-text">审核已完成！</span>
              </div>
            </div>
          </div>
          <br>

          <!-- 审核题目数据表格 -->
          <div class="review-data-table">
            <h4>审核题目数据</h4>
            
            <el-table :data="reviewedQuestions" border style="width: 100%" v-loading="tableLoading">
              <el-table-column prop="question" label="题目" width="400" show-overflow-tooltip></el-table-column>
              <el-table-column prop="answer" label="标准答案" width="325" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.answer }}
                </template>
              </el-table-column>
              <el-table-column prop="aiAnswer" label="大模型答案" width="325" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.aiAnswer }}
                </template>
              </el-table-column>
              <el-table-column label="审核结果" width="180">
                <template slot-scope="scope">
                  <div v-if="scope.row.type === 'choice' || scope.row.type === 'true_false'">
                    <el-tag :type="scope.row.score === 5 ? 'success' : 'danger'">
                      {{ scope.row.score === 5 ? '✓ 正确' : '✗ 错误' }}
                    </el-tag>
                  </div>
                  <div v-else-if="scope.row.type === 'short_answer'">
                    <div class="short-answer-score">
                      <span>{{ scope.row.swScore }}</span>分
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="题型" width="120">
                <template slot-scope="scope">
                  <el-tag :type="getTypeTagType(scope.row.type)">
                    {{ getTypeName(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页控件 -->
            <div class="pagination">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="reviewPage"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="reviewPageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="reviewTotal"
              >
              </el-pagination>
            </div>
          </div>
          <base-button 
            type="success" 
            class="mt-3" 
            @click="reportGenerate"
            :disabled="isEvaluating">生成评测报告</base-button>
        </card>
      </div>
    </div>
  </template>
  
  <script>
  import { Card } from "@/components/index";
  import StarRating from "vue-star-rating";
  import { Message } from "element-ui";
  import request from "../request.js";
  import { fetchQuestions ,fetchreviewedQuestions} from "../api/QuestionReview.js"
  import store from '@/store'; // 引入 Vuex 存储
import router from '@/router'; // 引入路由实例
  export default {
 
    components: { Card, StarRating },
    data() {
      return {
        
        questions:[],
        currentPage: 1,
        pageSize: 5,
        total: 0, // 题目总数
        progress: 0,
        autoReviewCompleted: false,
      
        showReviewDetails : false,
        progress: 0, // 实际进度（从后端获取）
        displayProgress: 0, // 显示进度（平滑过渡）
        isEvaluating: false,
        showCompletedProgress: false, // 完成后仍然显示进度条
        animationFrameId: null,
        socket: null, // WebSocket 连接
        reviewedQuestions: [],
        reviewPage: 1,
        reviewPageSize: 10,
        reviewTotal: 0,
        tableLoading: false,
      };
    },
    computed: {
      totalPages() {
        return Math.ceil(this.total / this.pageSize);
      },
      customColorMethod() {
      // 返回一个渐变色函数，使进度条更美观
      return (percentage) => {
        if (percentage < 30) {
          return '#f56c6c';
        } else if (percentage < 70) {
          return '#e6a23c';
        } else {
          return '#67c23a';
        }
      };
    },
    },
    methods: {
      reportGenerate(){
        router.push('/typography');
      },
      connectWebSocket() {
        const token = store.state.token;
        console.log("连接WebSocket，token:", token);

        // 关闭旧连接
        if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
          this.socket.close();
        }

        // 创建新连接
        this.socket = new WebSocket(`ws://localhost:8081/ws/review?token=${token}`);

        this.socket.onopen = () => {
          console.log("WebSocket 已连接");
          this.sendStartReviewRequest(); // WebSocket 连接成功后发送审核请求
        };

        this.socket.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data);
            console.log("收到WebSocket消息:", data);
            
            if (data.progress !== undefined) {
              // 解决精度问题，确保最多两位小数
              this.progress = parseFloat(data.progress);
              console.log("收到进度更新:", this.progress);
              
              // 进度条平滑更新
              this.smoothProgressUpdate();
              
              // 当收到100%进度时，设置审核完成状态并刷新题目数据
              if (this.progress >= 100) {
                this.autoReviewCompleted = true;
                this.isEvaluating = false;
                this.showCompletedProgress = true;
                
                // 审核完成后，重新获取题目数据
                setTimeout(() => {
                  this.fetchReviewedQuestions();
                }, 1000); // 延迟1秒，确保后端数据已更新
              }
            }
          } catch (e) {
            console.error("解析 WebSocket 消息失败:", e, event.data);
          }
        };

        this.socket.onclose = (event) => {
          console.log("WebSocket 连接关闭:", event.code, event.reason);
          // 意外关闭时的处理
          if (!this.autoReviewCompleted && this.isEvaluating) {
            Message.warning("与服务器的连接已断开，进度更新可能不准确");
          }
        };

        this.socket.onerror = (error) => {
          console.error("WebSocket 错误:", error);
          Message.error("连接评测服务器失败，请检查网络");
          this.isEvaluating = false;
        };
      },
      // 开始审核流程
      startReview() {
        if (this.isEvaluating) return;
        
        console.log("开始审核流程");
        this.isEvaluating = true;
        this.progress = 0;
        this.displayProgress = 0;
        this.showCompletedProgress = false;
        this.autoReviewCompleted = false;
        
        // 先连接WebSocket，连接成功后会自动调用sendStartReviewRequest
        this.connectWebSocket();
      },
      // 发送HTTP请求通知后端开始评测
      sendStartReviewRequest() {
        console.log("发送审核请求");
        request.get("/review/auto")
          .then(response => {
            console.log("审核请求发送成功:", response);
          })
          .catch(error => {
            console.error("审核请求失败:", error);
            this.isEvaluating = false;
            Message.error("审核模块启动失败！请稍后重试");
            
            // 关闭WebSocket连接
            if (this.socket) {
              this.socket.close();
            }
          });
      },
      // 平滑更新进度条
      smoothProgressUpdate() {
        // 取消之前的动画帧
        if (this.animationFrameId) {
          cancelAnimationFrame(this.animationFrameId);
        }

        const step = () => {
          // 计算显示进度与实际进度的差值
          const diff = this.progress - this.displayProgress;
          
          // 如果差值很小或已达到100%，直接设置为目标值
          if (Math.abs(diff) < 0.1 || this.progress >= 100) {
            this.displayProgress = this.progress;
            
            // 如果进度为100%，设置完成状态
            if (this.progress >= 100) {
              this.isEvaluating = false;
              this.showCompletedProgress = true;
              this.autoReviewCompleted = true;
              console.log("进度更新完成，已达到100%");
              return;
            }
          } else {
            // 否则平滑过渡
            this.displayProgress += diff * 0.1;
          }

          // 解决精度问题，最多保留两位小数
          this.displayProgress = Math.round(this.displayProgress * 100) / 100;
          
          // 继续下一帧
          this.animationFrameId = requestAnimationFrame(step);
        };

        // 开始动画
        this.animationFrameId = requestAnimationFrame(step);
      },
      async loadManuQuestions() {
        try {
          const response = await fetchQuestions({
            page: this.currentPage,
            size: this.pageSize ,
          });
          this.questions = response.data.items; // 只取 items 数组
          this.total = response.data.total; // 取 total 总数
        } catch (error) {
          Message.error("获取审核题目失败！");
        }
    },
    async submitManualReview(question) {
      try {
        const payload = {
          id: question.id,
          score: question.score,
        };

        await request.post("/review/submit", payload);
        Message.success("审核提交成功！");
      } catch (error) {
        Message.error("审核提交失败！");
      }
    },
      
      startAutoReview() {
        this.progress = 0;
        this.autoReviewCompleted = false;
        let interval = setInterval(() => {
          this.progress += 10;
          if (this.progress >= 100) {
            clearInterval(interval);
            this.autoReviewCompleted = true;
          }
        }, 500);
      },
      nextPage() {
        if (this.currentPage < this.totalPages) {
          this.currentPage++;
          this.loadManuQuestions();
        }
      },
      prevPage() {
        if (this.currentPage > 1) {
          this.currentPage--;
          this.loadManuQuestions();
        }
      },
      async fetchReviewedQuestions() {
        try {
          this.tableLoading = true;
          const response = await fetchreviewedQuestions({
            page: this.reviewPage,
            size: this.reviewPageSize,
          });
          this.reviewedQuestions = response.data.items;
          this.reviewTotal = response.data.total;
        } catch (error) {
          
        } finally {
          this.tableLoading = false;
        }
      },
      handleSizeChange(newSize) {
        this.reviewPageSize = newSize;
        this.reviewPage = 1; // 重置到第一页
        this.fetchReviewedQuestions();
      },
      handleCurrentChange(newPage) {
        this.reviewPage = newPage;
        this.fetchReviewedQuestions();
      },
      formatAnswer(row) {
        // 直接返回标准答案，不进行转换
        return row.answer;
      },
      getTypeName(type) {
        const typeMap = {
          'choice': '选择题',
          'true_false': '判断题',
          'short_answer': '简答题'
        };
        return typeMap[type] || type;
      },
      getTypeTagType(type) {
        const typeTagMap = {
          'choice': 'primary',
          'true_false': 'info',
          'short_answer': 'warning'
        };
        return typeTagMap[type] || '';
      },
    },
    mounted() {
    this.loadManuQuestions();
    this.fetchReviewedQuestions();
    },
  };
  </script>
  
  <style scoped>
 
 .manual-review {
  padding: 20px;
  background: #f8fbff;
  border-radius: 8px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
}
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  gap: 10px;
}
  
.review-data-table {
  margin-top: 20px;
}

.review-data-table h4 {
  margin-bottom: 15px;
  font-weight: 600;
  color: #333;
}

.progress-container {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.progress-label {
  font-weight: bold;
  color: #606266;
}

.progress-percentage {
  font-weight: bold;
  color: #409EFF;
}

.progress-status {
  margin-top: 10px;
  text-align: center;
  color: #606266;
}

.completed-text {
  color: #67C23A;
  font-weight: bold;
}

.custom-progress {
  margin-bottom: 10px;
}

/* 标签样式调整 */
.el-tag {
  margin-right: 5px;
}

.short-answer-score {
  font-weight: bold;
  color: #E6A23C;
  font-size: 16px;
  display: inline-block;
}

.short-answer-score span {
  margin-right: 4px;
}
  
  </style>
  
